﻿using System;
using System.Drawing;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Windows.Forms;

namespace NetBinder {
    public partial class MainForm : Form {
        public MainForm( ) {
            InitializeComponent( );
            this.T1.Start( );
            IPs( );
        }

        private void T1_Tick(object sender, EventArgs e) {
            Pinging( );
        }

        void Pinging( ) {
            if (System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable( )) {
                try {
                    PingReply pr = null;
                    string server = Properties.Settings.Default.Host;

                    using (Ping p = new Ping( )) {
                        int t = 10;
                        while (pr == null || (pr.Status == IPStatus.TimedOut && t <= 1000)) {
                            pr = p.Send(server, t);
                            t *= 5;
                        }
                    }

                    if (pr.Status == IPStatus.Success) {
                        Status = true;
                    } else {
                        Status = false;
                    }
                } catch (Exception ex) {
                    Status = false;
                }
            } else {
                Status = false;
            }
        }

        void IPs( ) {
            IPHostEntry IPHost = Dns.GetHostByName(Dns.GetHostName( ));
            LanIP = " ";
            LanIP = IPHost.AddressList[0].ToString( );
            WanIP = getPublicIP( );
        }

        private void B_save_Click(object sender, EventArgs e) {
            this.T1.Stop( );
            Properties.Settings.Default.Reload( );
            Properties.Settings.Default.Host = this.TB_host.Text;
            int result;
            if (Int32.TryParse(this.TB_interval.Text, out result))
                Properties.Settings.Default.Interval = result;
            this.T1.Interval = Properties.Settings.Default.Interval;
            Properties.Settings.Default.Save( );
            this.T1.Start( );
        }

        private void B_hide_Click(object sender, EventArgs e) {
            this.Visible = false;
            this.ShowInTaskbar = false;
            this.NI1.Visible = true;
            this.NI1.Icon = this.Icon;
        }

        private void NI1_DoubleClick(object sender, EventArgs e) {
            this.Visible = true;
            this.ShowInTaskbar = true;
            this.NI1.Visible = false;
        }

        private string _LanIP;
        public string LanIP { 
			get { return this._LanIP; } 
			set { this._LanIP = value; this.L_lan_ip.Text = value; }
		}
        private string _WanIP;
        public string WanIP { 
			get { return this._WanIP; } 
			set { this._WanIP = value; this.L_wan_ip.Text = value; } 
		}
        private bool _Status;
        public bool Status {
            get { return this._Status; }
            set { if (this._Status != value) { this._Status = value; this.Log( ); } this.NewText( ); }
        }
        private void NewText( ) {
            if (!this.Status) {
                L_status.Text = "Brak połączenia!";
                L_status.ForeColor = Color.Red;
                NI1.Text = this.Name + "\n" + "Brak połączenia!";
            } else {
                L_status.Text = "Połączono!";
                L_status.ForeColor = Color.Green;
            }
        }
        private void Log( ) {
            if (this.Status)
                NI1.ShowBalloonTip(500, "Status", "Connected!", ToolTipIcon.Info);
            else
                NI1.ShowBalloonTip(500, "Status", "Disconnected!", ToolTipIcon.Warning);
            FileStream fs = null;
            StreamWriter sw;
            if (!System.IO.File.Exists(Application.StartupPath + @"\NetBindder.txt")) {
                fs = File.Create(Application.StartupPath + @"\NetBindder.txt");
                sw = new StreamWriter(fs);
            } else {
                sw = File.AppendText(Application.StartupPath + @"\NetBindder.txt");
            }
            if (Status)
                sw.WriteLine(DateTime.Now.ToShortDateString( ) + " " + DateTime.Now.ToLongTimeString( ) + " LAN: " + LanIP + " WAN: " + WanIP + " Connected! (" + Properties.Settings.Default.Host + ")");
            else
                sw.WriteLine(DateTime.Now.ToShortDateString( ) + " " + DateTime.Now.ToLongTimeString( ) + " LAN: " + LanIP + " WAN: " + WanIP + " Disconnected! (" + Properties.Settings.Default.Host + ")");
            sw.Close( );
            if (fs != null)
                fs.Close( );
        }

        public static string getPublicIP( ) {
            string direction;
            WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
            WebResponse response = request.GetResponse( );
            StreamReader stream = new StreamReader(response.GetResponseStream( ));
            direction = stream.ReadToEnd( );
            stream.Close( );
            response.Close( );

            //Search for the ip in the html
            int first = direction.IndexOf("Address: ") + 9;
            int last = direction.LastIndexOf("</body>");
            direction = direction.Substring(first, last - first);

            return direction;
        }
    }
}